package com.aaa.car.service.impl;

import com.aaa.car.dao.OrderDao;
import com.aaa.car.entity.Order;
import com.aaa.car.service.RemoteMemberService;
import com.aaa.common.vo.OrderVo;
import com.aaa.car.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * (Order)表服务实现类
 *
 * @author lei chu
 * @since 2021-02-21 14:19:05
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;

    @Resource
    private RemoteMemberService remoteMemberService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Order queryById(Integer id) {
        return this.orderDao.queryById(id);
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param pageNum  当前页数
     * @param pageSize 每页条数
     * @param order    实例对象
     * @return 分页数据和信息
     */
    @Override
    public PageInfo<Order> queryAll(int pageNum, int pageSize, Order order) {
        return PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> this.orderDao.queryAll(order));
    }

    @Override
    public PageInfo<OrderVo> queryOrderVo(int pageNum, int pageSize, OrderVo orderVo) {
        return PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> this.orderDao.selectOrderVo(orderVo));
    }

    /**
     * 新增数据
     *
     * @param orderVo 实例对象
     * @return 实例对象
     */
    @Override
    public OrderVo insert(OrderVo orderVo) {
        Date date = new Date();
        orderVo.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
        orderVo.setOrderNo(new SimpleDateFormat("yyyyMMddHHmmss").format(date));

        //远程调用member 修改会员的余额和积分 需要返回抵扣积分的数量 一积分=一元钱
        double payMoney = this.remoteMemberService.updateAccountAndIntegration(orderVo.getMemberId(), orderVo.getTotalPrice());
        orderVo.setPreparidAmount(orderVo.getPreparidAmount() - payMoney);
        orderVo.setTotalPrice(orderVo.getTotalPrice() - payMoney);
        this.orderDao.insert(orderVo);

        return orderVo;
    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public Order update(Order order) {
        this.orderDao.update(order);
        return this.queryById(order.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.orderDao.deleteById(id) > 0;
    }

    /**
     * 通过会员Id查询该会员的订单，
     *
     * @param mid 会员ID
     * @return LIst
     */
    @Override
    public List<Order> queryOrderByMid(Integer mid) {
        return this.orderDao.queryOrderByMid(mid);
    }
}